package spring.diySpring;

import 注解.FruitName;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by zzy on 2018/4/22.
 */
public class ApllicationIOC {

    public static  Map<Object,Object> beanMap=new HashMap<>();

    public static List<String> beanName= Arrays.asList("BeanA","BeanB");


    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {


       String packageName = ApllicationIOC.class.getPackage().getName();
       for(String name:beanName){
           String trueName=packageName.concat(".").concat(name);
           Class theClass =  Class.forName(trueName);
           beanMap.put(toLowerCaseFirstOne(theClass.getSimpleName()),theClass.newInstance());
       }
        setProperty();

       BeanA beanA= (BeanA) beanMap.get("beanA");
       beanA.say();
    }

    public static String toLowerCaseFirstOne(String s){
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    private static void setProperty() throws IllegalAccessException {
        for(Map.Entry<Object,Object> entry : beanMap.entrySet()){
             //获取对象的域
            Object theObj= entry.getValue();
            Field[]  fields=theObj.getClass().getDeclaredFields();
            //查看域的注解
            for(Field field:fields){
                if(field.isAnnotationPresent(AutoInto.class)==true){//使用了AutoInto
                    AutoInto autoInto=field.getAnnotation(AutoInto.class);
                    if(autoInto.into()){//需要自动注入
                     String name= field.getName();
                     field.setAccessible(true);
                     field.set(theObj,beanMap.get(name));
                    }
                }
            }
        }
    }

}
